import { getSorter, useRequestHandle } from '@/utils/utils';
import {
    PlusOutlined,
} from '@ant-design/icons';
import { ProDescriptions } from '@ant-design/pro-components';
import {
    Button,
    Drawer,
    message,
    Space, Steps, Segmented, Modal, Tag
} from 'antd';
import { useRef, useState } from 'react';
import { Access, useAccess, history } from 'umi';
import SaveForm from './components/SaveForm';
import operation from './operation';
import { startPublish, query, cancelPublish, restorePublish, completePublish } from './service';
import ProMaxTable from '@/components/ProMaxTable';
import { useUpdateEffect } from '@umijs/hooks';

const { confirm } = Modal;

const X = () => {
    const [saveFormVisible, setSaveFormVisible] = useState(false);
    const [updateFormValues, setUpdateFormValues] = useState({});
    const actionRef = useRef();
    const [row, setRow] = useState();
    const { canOperation, canShowOption } = useAccess();
    const [flowStatus, setFlowStatus] = useState(2);
    // 是否显示操作列
    const isShowOptionColumn = canShowOption([
        operation.startPublish
    ]);

    // 刷新
    const reload = () => {
        if (actionRef.current) {
            actionRef.current.reload();
        }
    };

    // 新增/修改
    const startPublishRequest = useRequestHandle(startPublish, (data) => {
        message.success('创建成功.');
        setSaveFormVisible(false);
        // reload();
        history.push(`/system/developer/applications/publishflow/${data}`);
    });

    const cancelPublishRequest = useRequestHandle(cancelPublish, () => {
        message.success('取消成功.');
        reload();
    });

    const restorePublishRequest = useRequestHandle(restorePublish, () => {
        message.success('还原成功.');
        reload();
    });
    const completePublishRequest = useRequestHandle(completePublish, () => {
        message.success('完成成功.');
        reload();
    });

    useUpdateEffect(() => {
        reload();
    }, [flowStatus])




    const items = [
        {
            title: '备份'
        },
        {
            title: '上传'
        },
        {
            title: '发布'
        },
        {
            title: '脚本'
        },
    ];


    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            valueType: 'indexBorder',
            fixed: 'left',
            width: 75,
        },
        {
            title: '服务器名称',
            dataIndex: 'agentServerName',
            ellipsis: true,
            render: (dom, entity) => <a onClick={() => setRow(entity)}>{dom}</a>,
            fixed: 'left',
            width: 170,
        },
        {
            title: '服务名称',
            dataIndex: 'agentServiceName',
            ellipsis: true,
        },
        {
            title: '版本名称',
            dataIndex: 'name',
            ellipsis: true,

        },
        {
            title: '版本内容',
            dataIndex: 'context',
            ellipsis: true,

        },
        {
            title: '状态',
            dataIndex: 'publishFlowStatus',
            ellipsis: true,
            width: 60,
            render: (_, record) => {
                switch (record.publishFlowStatus) {
                    case 2:
                        return <Tag color='processing'>进行中</Tag>;
                    case 3:
                        return <Tag color='error'>已取消</Tag>;
                    case 4:
                        return <Tag color='success'>已完成</Tag>;
                    case 5:
                        return <Tag color='warning'>已还原</Tag>;
                    default:
                        return <Tag color=''>未知</Tag>;
                }
            }

        },
        {
            title: '进度',
            dataIndex: 'status',
            ellipsis: true,
            width: 200,
            render: (_, record) => {
                return <Steps
                    type="inline"
                    current={record.nodes.length}
                    items={items}
                />
            }
        },
        {
            title: '创建时间',
            dataIndex: 'created',
            ellipsis: true,

        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            hideInTable: !isShowOptionColumn,
            width: 180,
            render: (_, record) => (
                <Space>
                    <Access accessible={canOperation(operation.query)}>


                        <Button
                            type="primary"
                            size="small"
                            onClick={async () => {
                                history.push(`/system/developer/applications/restore/${record.id}`);
                            }}
                        >
                            查看
                        </Button>
                    </Access>
                    <Access accessible={canOperation(operation.startPublish) && record.publishFlowStatus === 2}>


                        <Button
                            type="primary"
                            size="small"
                            onClick={async () => {
                                history.push(`/system/developer/applications/publishflow/${record.id}`);
                            }}
                        >
                            {"发布"}
                        </Button>
                    </Access>
                    <Access accessible={canOperation(operation.restorePublish)
                        && record.publishFlowStatus !== 3
                        && record.publishFlowStatus !== 5
                        && record.nodes.length > 2}>
                        <Button
                            type="dashed"
                            size="small"
                            danger
                            loading={restorePublishRequest.loading}
                            onClick={async () => {
                                confirm({
                                    title: '确认要还原发布?',
                                    content: '还原后，将会把备份文件还原到服务器上，请注意有没有其他备份，以免版本错误！',
                                    onOk() {
                                        restorePublishRequest.run({ id: record.id });
                                    },
                                    onCancel() {

                                    },
                                });
                            }}
                        >
                            还原
                        </Button>
                    </Access>
                    <Access accessible={canOperation(operation.cancelPublish) && record.publishFlowStatus === 2 && record.nodes.length <= 2}>
                        <Button
                            type="dashed"
                            size="small"
                            danger
                            loading={cancelPublishRequest.loading}
                            onClick={async () => {
                                confirm({
                                    title: '确认要取消发布?',
                                    content: '确认要取消发布？ ',
                                    onOk() {
                                        cancelPublishRequest.run({ id: record.id });
                                    },
                                    onCancel() {

                                    },
                                });
                            }}
                        >
                            取消
                        </Button>
                    </Access>
                    <Access accessible={canOperation(operation.completePublish)
                        && record.publishFlowStatus === 2
                        && record.nodes.length >= 3
                    }>
                        <Button
                            type="primary"
                            size="small"
                            ghost
                            loading={completePublishRequest.loading}
                            onClick={async () => {
                                confirm({
                                    title: '确认完成发布?',
                                    content: '完成后无法在进行脚本执行，是否确认完成？',
                                    onOk() {
                                        completePublishRequest.run({ id: record.id });
                                    },
                                    onCancel() {

                                    },
                                });
                            }}
                        >
                            完成
                        </Button>
                    </Access>
                </Space >
            ),
        },
    ];
    return (
        <>

            <ProMaxTable
                headerTitle={<Segmented
                    value={flowStatus}
                    options={[{ label: '全部', value: null }, { label: '进行中', value: 2 }, { label: '已完成', value: 4 }, { label: '已取消', value: 3 }, { label: '已还原', value: 5 }
                    ]}
                    onChange={(value) => {
                        setFlowStatus(value);
                    }}
                />}
                actionRef={actionRef}
                cardProps={{
                    style: { height: "auto" }
                }}
                rowKey="id"
                search={false}
                options={{
                    search: canOperation(operation.query)
                        ? {
                            placeholder: '请输入关键字',
                        }
                        : false,
                    fullScreen: true,
                }}
                toolBarRender={() => [
                    <Access key="create" accessible={canOperation(operation.startPublish)}>
                        <Button type="primary" onClick={() => {

                            setSaveFormVisible(true)

                        }}>
                            <PlusOutlined /> 版本发布
                        </Button>
                    </Access>,

                ]}
                request={async (params, sorter, filter) => {
                    const data = params;
                    data.pageIndex = params.current;
                    data.publishFlowStatus = flowStatus;
                    const result = await query({ ...data, ...getSorter(sorter), filter });
                    if (result.success) {
                        return {
                            ...result,
                            total: result.data.totalItems,
                        };
                    }
                    return [];
                }}
                postData={(data) => {
                    return !data ? [] : data.items;
                }}
                // scroll={{
                //   x: 1200,
                // }}
                columns={columns}
                rowSelection={false}
                expandable={{ defaultExpandAllRows: true }}
            />

            <SaveForm
                onSubmit={async (value) => {
                    const params = { ...value }
                    startPublishRequest.run(params);
                }}
                onCancel={() => {
                    setSaveFormVisible(false);
                    setUpdateFormValues({});
                }}
                loading={startPublishRequest.loading}
                modalVisible={saveFormVisible}
                record={updateFormValues}
            />

            <Drawer
                width={600}
                open={!!row}
                onClose={() => {
                    setRow(undefined);
                }}
                closable={false}
            >
                {row?.id && (
                    <ProDescriptions
                        column={2}
                        title={row?.realName}
                        request={async () => ({
                            data: row || {},
                        })}
                        params={{
                            id: row?.id,
                        }}
                        columns={columns}
                    />
                )}
            </Drawer>


        </>
    );
};

export default X;
